<?php
/**
 * @author spenceryg
 * @date 2023/3/18
 * @time 1:10 下午
 * @focus love & life
 */


namespace app\api\controller;
use app\common\lib\verify\VerifyFactory;
use app\common\model\ArticleClass;
use app\common\model\MemberLoginLog;
use app\common\model\Orders;
use app\common\model\PointProducts;
use EasyWeChat\Factory;
use hg\apidoc\annotation as Apidoc;
use thans\jwt\facade\JWTAuth;
use Yansongda\Pay\Pay;


/**
 * Class Member
 * @package app\api\controller
 * @Apidoc\Title ("会员管理")
 */
class Member extends Auth
{



    /**
     * @Apidoc\Title ("我的客户")
     * myCustomers
     */
    public function myCustomers(): \think\response\Json
    {
        $list_rows = input('list_rows', 10, 'intval');
        $data = \app\common\model\Member::where('promoter_id', $this->request->uid)
            ->append(['money'])
            ->withAttr('money', function($value, $data) {
                return Orders::where('member_id', $data['id'])->sum('total_amount');
            })
            ->field(['name', 'create_time', 'id'])->order('id desc')->paginate($list_rows);
        return success('', $data);
    }

    /**
     * getShare
     * @Apidoc\Title ("获取分享")
     */
    public function getShare(): \think\response\Json
    {
        $id = $this->request->uid;
        $config = config('pull_new_gifts');
        $arr = explode("\r\n",  trim($config['sharing_address']));
        $inviteList = [];
        foreach ($arr as $item) {
           [$title, $url ] = explode('__', $item);
            $inviteList[] = [
                'title' => $title,
                'url' => $url . substr(sha1($id), -8)
            ];
        }
        $config['inviteList'] = $inviteList;
        return success('', $config);
    }


    private function encrypt($data, $key = 'mysecretkey1234567890') {
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv);
        return base64_encode($encrypted . '___' . $iv);
    }

    private function decrypt($data, $key = 'mysecretkey1234567890') {
        list($encrypted_data, $iv) = explode('___', base64_decode($data), 2);
        return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
    }


    /**
     * getInfo
     * @Apidoc\Title("获取会员信息")
     */
    public function getInfo(): \think\response\Json
    {
        $res = \app\common\model\Member::with(['memberInformation', 'articleClass'])->find($this->request->uid);
        return success('ok', $res);
    }




    /**
     * update
     * @return \think\response\Json
     * @Apidoc\Title("更新会员信息")
     */
    public function update()
    {
        /******************言论审查开始***********************************/
        //数据检验开始，这里审查用户的言论是否符合国家法律规定，这里一定要加上++++++++++++++++++++++++++++++++++++++++++++++++++++++
        $TextModeration=new \app\api\service\TextModerationService();
        if (!$TextModeration->check(json_encode($this->request->param(),JSON_UNESCAPED_UNICODE))) {
            return error($TextModeration->msg);
        }
        /*****************言论审查结束了**********************************/
        $data = $this->request->post(['name', 'province', 'address']);
        validate(['name|昵称' => 'require'])->check($data);
        \app\common\model\Member::where('id', $this->request->uid)->save($data);
        return success();
    }

    /**
     * logout
     * @Apidoc\Title("退出登录")
     */
    public function logout(): \think\response\Json
    {
        $token = str_replace('Bearer ', '', $this->request->header('Authorization'));
        JWTAuth::invalidate($token);
        return success();
    }

    /**
     * loginLog
     * @Apidoc\Title("登录日志")
     */
    public function loginLog()
    {
        $list_rows = input('list_rows', 10, 'intval');
        $res = MemberLoginLog::where('member_id', $this->request->uid)->order('id desc')->paginate($list_rows);
        return success('', $res);
    }


    /**
     * checkEmailStep1
     * @Apidoc\Title("验证修改邮箱第一步")
     */
    public function checkEmailStep1()
    {
        $data = input();
        validate([
            'phone|邮箱' => 'require',
            'code|验证码' => 'require'
        ])->check($data);
        VerifyFactory::verify($data['phone'], $data['code']);
        cache('email_step2_' . $this->request->uid, true, 600);
        return success();
    }

    /**
     * checkEmailStep2
     * @Apidoc\Title("验证修改邮箱第二步")
     */
    public function checkEmailStep2()
    {
        $data = input();
        validate([
            'email|邮箱' => 'require',
            'code|验证码' => 'require'
        ])->check($data);
        VerifyFactory::verify($data['email'], $data['code']);
        $member = \app\common\model\Member::find($this->request->uid);
        $member->email = $data['email'];
        $member->save();
        cache('email_step2_' . $this->request->uid, null);
        return success();
    }

    /**
     * canEmailStep2
     * @Apidoc\Title("能否修改邮箱第二步")
     */
    public function canEmailStep2()
    {
        $email = \app\common\model\Member::where('id', $this->request->uid)->value('email');
        return success('', (bool)cache('email_step2_' . $this->request->uid) || !$email);
    }



    /**
     * checkPhoneStep1
     * @Apidoc\Title("验证修改手机第一步")
     */
    public function checkPhoneStep1()
    {
        $data = input();
        validate([
            'phone|手机号码' => 'require',
            'code|验证码' => 'require'
        ])->check($data);
        VerifyFactory::verify($data['phone'], $data['code']);
        cache('phone_step2_' . $this->request->uid, true, 600);
        return success();
    }

    /**
     * checkPhoneStep2
     * @Apidoc\Title("验证修改手机第二步")
     */
    public function checkPhoneStep2()
    {
        $data = input();
        validate([
            'phone|手机号码' => 'require',
            'code|验证码' => 'require'
        ])->check($data);
        VerifyFactory::verify($data['phone'], $data['code']);
        $member = \app\common\model\Member::find($this->request->uid);
        $member->phone = $data['phone'];
        $member->save();
        cache('phone_step2_' . $this->request->uid, null);
        return success();
    }

    /**
     * canPhoneStep2
     * @Apidoc\Title("能否修改手机第二步")
     */
    public function canPhoneStep2()
    {
        return success('', (bool)cache('phone_step2_' . $this->request->uid));
    }


    /**
     * miniPay
     * @Apidoc\Title("小程序支付")
     * @return \think\response\Json|void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function miniPay()
    {
        $code = input('code');
        $id = input('id');
        if(!$code || !$id){
            return error('参数错误！');
        }

        $config = [
            'app_id' => config('front_end.app_id'),
            'secret' => config('front_end.secret'),
            'response_type' => 'array',
        ];
        $app = Factory::miniProgram($config);
        $session = $app->auth->session($code);  // $code 是前端传递的登录凭证
        $openId = $session['openid'];


        $product = PointProducts::find($id);
        $subject = 'aidog充值购买' . ($product['integral'] + $product['reward_points']) .'积分';
        if($product['is_integral']){
            $subject =  'aidog充值购买' . $product['name'];
        }
        $result =  Pay::wechat(config('wechat_payment'))->miniapp([
            'out_trade_no' => $this->request->uid. '_' . $id .  '_' . time(),
            'total_fee' => $product['money'] * 100,
//            'total_fee' => 1,
            'body' => $subject,
            'openid' => $openId
        ]);
//        return success('',$session);
        return success('', $result);
    }


}
